<template>
    <div class="app-container">
        <el-card>
            <el-page-header @back="goBack">
                <template #content>
                    <div class="flex items-center">
                        <div v-if="!route.query?.id">新增设备</div>
                        <div v-else>
                            <span class="text-sm mr-2" style="color: var(--el-text-color-regular)">
                                设备编码:
                            </span>
                            <el-tag :type="form.status == 1 ? 'danger' : ''">
                                {{ form.machineNo }}
                            </el-tag>
                        </div>
                    </div>
                </template>
                <template #extra>
                    <div class="flex items-center" v-if="!route.query.info">
                        <el-button type="primary" @click="submitForm">保 存</el-button>
                    </div>
                </template>
            </el-page-header>
        </el-card>
        <el-card style="margin-top: 10px">
            <el-collapse v-model="activeNames">
                <el-collapse-item disabled title="基本信息" name="1">
                    <template #title>
                        <el-icon style="color: #4479f6">
                            <Position />
                        </el-icon>
                        <span class="title">基本信息</span>
                    </template>
                    <div :class="{ 'layout-code': flag }">
                        <div>
                            <el-form
                                :model="form"
                                :rules="rules"
                                :disabled="flag"
                                ref="userRef"
                                label-width="100px"
                            >
                                <el-row :gutter="20">
                                    <el-col :span="8">
                                        <el-form-item label="设备名称" prop="machineName">
                                            <el-input
                                                v-model="form.machineName"
                                                placeholder="请输入设备名称"
                                                maxlength="30"
                                            />
                                        </el-form-item>
                                    </el-col>

                                    <el-col :span="8">
                                        <el-form-item label="车间编号" prop="workshopNo">
                                            <el-input
                                                v-model="form.workshopNo"
                                                readonly
                                                @click="openWorkDialog"
                                                placeholder="点击选择车间"
                                                maxlength="18"
                                            />
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="8">
                                        <el-form-item label="车间名称" prop="workshopName">
                                            <el-input
                                                v-model="form.workshopName"
                                                disabled
                                                placeholder="自动带出"
                                            />
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row :gutter="20">
                                    <el-col :span="8">
                                        <el-form-item label="版材尺寸" prop="size">
                                            <el-select
                                                style="width: 100%"
                                                v-model="form.size"
                                                class="m-2"
                                                placeholder="请选择版材尺寸"
                                            >
                                                <el-option
                                                    v-for="item in ems_machine_info_size"
                                                    :key="item.value"
                                                    :label="item.label"
                                                    :value="item.value"
                                                />
                                            </el-select>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="8">
                                        <el-form-item label="机型" prop="model">
                                            <el-select
                                                style="width: 100%"
                                                v-model="form.model"
                                                class="m-2"
                                                placeholder="请选择机型"
                                            >
                                                <el-option
                                                    v-for="item in ems_machine_info_model"
                                                    :key="item.value"
                                                    :label="item.label"
                                                    :value="item.value"
                                                />
                                            </el-select>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="8">
                                        <el-form-item label="损耗比例(%)" prop="wasteRate">
                                            <el-select
                                                style="width: 100%"
                                                v-model="form.wasteRate"
                                                class="m-2"
                                                placeholder="请选择损耗比例"
                                            >
                                                <el-option
                                                    v-for="item in ems_machine_info_waste_rate"
                                                    :key="item.value"
                                                    :label="item.label"
                                                    :value="item.value"
                                                />
                                            </el-select>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row :gutter="20">
                               
                                    <!-- <el-col :span="8">
                                        <el-form-item label="机长" prop="headUserName">
                                            <el-input
                                                v-model="form.headUserName"
                                                readonly
                                                @click="openDialog"
                                                placeholder="点击选择机长"
                                            />
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="8">
                                        <el-form-item label="机长电话" prop="headUserPhone">
                                            <el-input
                                                v-model="form.headUserPhone"
                                                disabled
                                                placeholder="自动带出"
                                            />
                                        </el-form-item>
                                    </el-col> -->
                                </el-row>
                                <el-row :gutter="20">
                                    <el-col :span="8">
                                        <el-form-item label="类型" prop="type">
                                            <el-select
                                                style="width: 100%"
                                                v-model="form.type"
                                                class="m-2"
                                                placeholder="请选择类型"
                                                @blur="changeType(form.type)"
                                            >
                                                <el-option
                                                    v-for="item in ems_machine_info_type"
                                                    :key="item.value"
                                                    :label="item.label"
                                                    :value="item.value"
                                                />
                                            </el-select>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="8">
                                        <el-form-item label="机台贴数" prop="stickNumber">
                                            <el-input
                                                type="number"
                                                v-model="form.stickNumber"
                                                placeholder="请输入机台贴数"
                                                maxlength="30"
                                            />
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="8">
                                        <el-form-item label="名称" prop="wheelName">
                                            <el-select
                                                style="width: 100%"
                                                v-model="form.wheelName"
                                                multiple
                                                class="m-2"
                                                placeholder="请选择名称"
                                            >
                                                <el-option
                                                    v-for="item in ems_machine_info_wheel_name"
                                                    :key="item.value"
                                                    :label="item.label"
                                                    :value="item.value"
                                                />
                                            </el-select>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row :gutter="20">
                                    <el-col :span="8">
                                        <el-form-item label="产能(令/时)" prop="capacity">
                                            <el-input
                                                type="number"
                                                v-model="form.capacity"
                                                placeholder="请输入产能(令/时)"
                                                maxlength="30"
                                            />
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="8">
                                        <el-form-item label="类别" prop="category">
                                            <el-select
                                                style="width: 100%"
                                                v-model="form.category"
                                                class="m-2"
                                                multiple
                                                placeholder="请选择类别"
                                            >
                                                <el-option
                                                    v-for="item in ems_machine_info_category"
                                                    :key="item.value"
                                                    :label="item.label"
                                                    :value="item.value"
                                                />
                                            </el-select>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="8" v-if="eraFlag">
                                        <el-form-item
                                            label="半代/整代"
                                            prop="era"
                                            :rules="[
                                                {
                                                    required: true,
                                                    message: '半代/整代不能为空',
                                                    trigger: 'blur',
                                                },
                                            ]"
                                        >
                                            <el-select
                                                style="width: 100%"
                                                v-model="form.era"
                                                class="m-2"
                                                placeholder="请选择半代/整代"
                                            >
                                                <el-option
                                                    v-for="item in eraOptions"
                                                    :key="item.value"
                                                    :label="item.label"
                                                    :value="item.value"
                                                />
                                            </el-select>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row :gutter="20">
                                    <el-col :span="24">
                                        <el-form-item label="备注">
                                            <el-input
                                                v-model="form.remark"
                                                type="textarea"
                                                placeholder="请输入内容"
                                            ></el-input>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                            </el-form>
                        </div>
                        <div v-if="flag">
                            <el-form-item>
                                <div class="code">
                                    <div class="code-box">
                                        <vue-qr
                                            :text="qrCode"
                                            :size="180"
                                            style="display: block; margin: auto"
                                        ></vue-qr>
                                        <div class="title">
                                            <div style="margin-right: 16px">
                                                {{ form.machineNo }}
                                            </div>
                                            <div>{{ form.machineName }}</div>
                                        </div>
                                        <div class="title">
                                            <span style="margin-right: 16px">所属车间:</span>
                                            {{ form.workshopName }}
                                        </div>
                                    </div>
                                </div>
                            </el-form-item>
                        </div>
                    </div>
                </el-collapse-item>
            </el-collapse>
        </el-card>

        <el-card style="margin-top: 10px">
            <el-collapse v-model="activeNames">
                <el-collapse-item disabled title="机台成员" name="1">
                    <template #title>
                        <el-icon style="color: #4479f6">
                            <Position />
                        </el-icon>
                        <span class="title">机台成员</span>
                    </template>
                    <el-button
                        v-if="!flag"
                        style="margin-bottom: 5px"
                        type="primary"
                        size="small"
                        plain
                        icon="Plus"
                        @click="handleAdd"
                    >
                        新增
                    </el-button>
                    <el-table :data="mesMachineUserList" border style="width: 100%">
                        <el-table-column
                            type="index"
                            label="序号"
                            width="80"
                            align="center"
                        ></el-table-column>
                        <el-table-column prop="team" label="班组" align="center">
                            <template #default="scope">
                                <el-select
                                    :disabled="flag"
                                    style="width: 100%"
                                    v-model="scope.row.team"
                                    class="m-2"
                                    placeholder="请选择班组"
                                >
                                    <el-option
                                        v-for="item in ems_team"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value"
                                    />
                                </el-select>
                            </template>
                        </el-table-column>
                        <el-table-column
                            prop="code"
                            label="员工编号"
                            align="center"
                        ></el-table-column>
                        <el-table-column prop="name" label="姓名" align="center"></el-table-column>
                        <el-table-column
                            prop="telephone"
                            label="联系方式"
                            align="center"
                        ></el-table-column>
                        <el-table-column prop="position" label="职位" align="center">
                            <template #default="scope">
                                <el-select
                                    :disabled="flag"
                                    style="width: 100%"
                                    v-model="scope.row.position"
                                    class="m-2"
                                    placeholder="请选择职位"
                                >
                                    <el-option
                                        v-for="item in ems_machine_info_position"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value"
                                    />
                                </el-select>
                            </template>
                        </el-table-column>
                        <el-table-column prop="proportion" label="岗位占比" align="center">
                            <template #default="scope">
                                <el-input type="number"   @input="limitInput('proportion', scope.row)" :disabled="flag" v-model="scope.row.proportion"></el-input>
                            </template>
                        </el-table-column>
                        <el-table-column prop="remark" label="备注" align="center">
                            <template #default="scope">
                                <el-input :disabled="flag" v-model="scope.row.remark"></el-input>
                            </template>
                        </el-table-column>
                        <el-table-column
                            fixed="right"
                            v-if="!flag"
                            label="操作"
                            width="100"
                            align="center"
                        >
                            <template #default="scope">
                                <el-button
                                    link
                                    type="primary"
                                    @click="handelDelUser(scope.row)"
                                    size="small"
                                >
                                    删除
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-collapse-item>
            </el-collapse>
        </el-card>
        <el-dialog v-model="dialogVisible" title="人员列表" width="60%" @close="close">
            <el-form :model="queryParams" ref="queryRef" :inline="true">
                <el-form-item label="员工编码" prop="code">
                    <el-input
                        v-model.trim="queryParams.code"
                        placeholder="请输入员工编码"
                        @keyup.enter="handleQuery"
                    />
                </el-form-item>
                <el-form-item label="姓名" prop="name">
                    <el-input
                        v-model.trim="queryParams.name"
                        placeholder="请输入姓名"
                        @keyup.enter="handleQuery"
                    />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                    <el-button icon="Refresh" @click="resetQuery">重置</el-button>
                </el-form-item>
            </el-form>
            <el-table
                v-loading="loading"
                :data="userList"
                stripe
                border
                style="cursor: pointer"
                @cell-click="handleCellClick"
            >
                <el-table-column label="序号" width="80" type="index" align="center" />
                <el-table-column
                    label="员工编号"
                    min-width="120"
                    align="center"
                    :show-overflow-tooltip="true"
                    prop="code"
                ></el-table-column>
                <el-table-column
                    label="姓名"
                    align="center"
                    :show-overflow-tooltip="true"
                    prop="name"
                ></el-table-column>
                <el-table-column
                    label="联系方式"
                    align="center"
                    :show-overflow-tooltip="true"
                    prop="telephone"
                ></el-table-column>
            </el-table>
            <div class="footer">
                <pagination
                    v-show="total > 0"
                    :total="total"
                    v-model:page="queryParams.pageNum"
                    v-model:limit="queryParams.pageSize"
                    @pagination="getUserList"
                />
            </div>
        </el-dialog>
        <workshopList
            :visible="visibleWorkOpen"
            @changeUpdate="changeData"
            @cancel="
                () => {
                    visibleWorkOpen = false
                }
            "
        ></workshopList>
        <userLists
            ref="userListDOM"
            :visible="visibleUserOpen"
            @changeUpdate="changeUserData"
            :userSelectList="userSelectList"
            @cancel="
                () => {
                    visibleUserOpen = false
                }
            "
        ></userLists>
    </div>
</template>

<script setup>
import useTagsViewStore from '@/store/modules/tagsView'
import { getMesUserInfo } from '@/api/basicInfo/personnel'
import { ElMessage } from 'element-plus'
import { addList, getById } from '@/api/basicInfo/workbench'
import workshopList from './workshopList.vue'
import userLists from './userLists.vue'
import vueQr from 'vue-qr/src/packages/vue-qr.vue'
const tagsViewStore = useTagsViewStore()
const router = useRouter()
const route = useRoute()
const activeNames = ['1']
const { proxy } = getCurrentInstance()
const userRef = ref(null)
const qrCode = ref('')
const flag = ref(false)
const eraFlag = ref(false)
const dialogVisible = ref(false)
const visibleWorkOpen = ref(false)
const visibleUserOpen = ref(false)
const userList = ref([])
const loading = ref(false)
const userListDOM = ref(null)
const userSelectList = ref([])
const notRequired = ref(false)
const eraOptions = ref([
    {
        value: '1',
        label: '半代',
    },
    {
        value: '2',
        label: '整代',
    },
])
const queryParams = ref({
    pageNum: 1,
    pageSize: 10,
    joinPositionStatus: 1,
})
const total = ref(0)
const data = reactive({
    value: '',
    form: {},
    rules: {
        machineName: [{ required: true, message: '设备名称不能为空', trigger: 'blur' }],
        type: [{ required: true, message: '类型不能为空', trigger: ['blur', 'change'] }],
        wasteRate: [
            { required: true, message: '损耗比例(%)不能为空', trigger: ['blur', 'change'] },
        ],
        capacity: [{ required: true, message: '产能不能为空', trigger: 'blur' }],
        // 产能 机台贴数 名称
    },
    mesMachineUserList: [],
})

const { form, rules, mesMachineUserList } = toRefs(data)

const {
    ems_team,
    ems_machine_info_size,
    ems_machine_info_waste_rate,
    ems_machine_info_wheel_name,
    ems_machine_info_category,
    ems_machine_info_model,
    ems_machine_info_position,
    ems_machine_info_type,
} = proxy.useDict(
    'ems_team',
    'ems_machine_info_position',
    'ems_machine_info_category',
    'ems_machine_info_wheel_name',
    'ems_machine_info_size',
    'ems_machine_info_waste_rate',
    'ems_machine_info_model',
    'ems_machine_info_type'
)
watch(
    () => route,
    (newValue, oldValue) => {
        if (newValue.query?.id) {
            getById({ pid: newValue.query.id }).then(res => {
                if (res.data.type == 4) {
                    //显示字段
                    eraFlag.value = true
                    notRequired.value = true
                }
                Object.assign(form.value, { ...res.data })
                form.value.wheelName = res.data.wheelName ? res.data.wheelName?.split(',') : null
                if(res.data.category) {
                    form.value.category = res.data.category?.split(',')
                }
                // qrCode.value = `http://47.104.229.186:8241/todo?id=${newValue.query.id}`
                // qrCode.value = `http://192.168.3.177:30208/todo?id=${newValue.query.id}`
                qrCode.value = `http://222.132.97.42:30208/todo?id=${newValue.query.id}`
                // qrCode.value = import.meta.env.VITE_APP_BASE_API + `/todo?id=${newValue.query.id}`
                mesMachineUserList.value = res.data.mesMachineUserList.map(item => {
                    return {
                        ...item.mesUsers,
                        ...item,
                    }
                })
                if (newValue.query.info) {
                    flag.value = true
                }
            })
        }
    },
    { immediate: true }
)

//限制只能输入4位小数
function limitInput(key, row) {
    row[key] =
        ('' + row[key]) // 第一步：转成字符串
            .replace(/[^\d^\.]+/g, '')
            .replace(/^0+(\d)/, '$1')
            .replace(/^\./, '0.')
            .match(/^\d*(\.?\d{0,1})/g)[0] || ''
}
//  返回
const goBack = () => {
    tagsViewStore.delView(route)
    if (route.query.moduleCode == 'textDetails') {
        router.push({
            path: '/production/text/textDetails',
            query: {
                id: route.query.produceId,
                info: true,
            },
        })
    } else if (route.query.moduleCode == 'converDetails') {
        router.push({
            path: '/production/cover/coverDetails',
            query: {
                id: route.query.produceId,
                info: true,
            },
        })
    } else {
        router.push('/basicInfo/workbench')
    }

    // router.go(-1)
}
const close = () => {
    proxy.resetForm('queryRef')
}

// 选择在职人员
const openDialog = () => {
    dialogVisible.value = true
    getUserList()
}
// 搜索
const handleQuery = () => {
    queryParams.value.pageNum = 1
    getUserList()
}
//设备类型，如果是折页，需要展示半代（1）   整代（2）
const changeType = type => {
    //debugger
    if (type == 4) {
        //显示字段
        eraFlag.value = true
        notRequired.value = true
    } else {
        eraFlag.value = false
        notRequired.value = false
    }
}
/** 重置按钮操作 */
const resetQuery = () => {
    proxy.resetForm('queryRef')
    handleQuery()
}

// 选中当前行
const handleCellClick = row => {
    proxy.$modal
        .confirm('是否确认选择「' + row.name + '」')
        .then(function () {
            form.value.headUser = row.id
            form.value.headUserName = row.name
            form.value.headUserPhone = row.telephone
            dialogVisible.value = false
        })
        .catch(() => {})
}

const getUserList = async () => {
    loading.value = true
    const res = await getMesUserInfo(queryParams.value)
    loading.value = false
    userList.value = res.rows
    total.value = res.total
}
// 车间选择
const openWorkDialog = () => {
    visibleWorkOpen.value = true
}
const changeData = row => {
    form.value.workshopId = row.id
    form.value.workshopName = row.name
    form.value.workshopNo = row.code
    visibleWorkOpen.value = false
}
const changeUserData = row => {
    const codeSet = new Set(mesMachineUserList.value.map(data => data.code))
    row.forEach(item => {
        if (!codeSet.has(item.code)) {
            mesMachineUserList.value.push({
                userId: item.id,
                name: item.name,
                code: item.code,
                telephone: item.telephone,
            })
            codeSet.add(item.code)
        }
    })

    visibleUserOpen.value = false
}
const handelDelUser = row => {
    proxy.$modal
        .confirm('是否确认删除"' + row.name + '"')
        .then(function () {
            mesMachineUserList.value = mesMachineUserList.value.filter(
                item => item.code !== row.code
            )
        })
        .catch(() => {})
}

const handleAdd = () => {
    visibleUserOpen.value = true
    userSelectList.value = mesMachineUserList.value
}

// 确认
const submitForm = () => {
    form.value.wheelName =form.value.wheelName ? form.value.wheelName?.join(',') :form.value.wheelName
    form.value.category =form.value.category ? form.value.category?.join(',') :form.value.category
    if(form.value.category==''){
      form.value.category=null
    }
    userRef.value.validate(valid => {
        if (valid) {
            if (!route.query?.id) {
                form.value.status = 2
            }
            addList({ ...form.value,mesMachineUserList: mesMachineUserList.value }).then(res => {
                if (route.query.id) {
                    ElMessage({
                        message: '编辑成功',
                        type: 'success',
                    })
                } else {
                    ElMessage({
                        message: '新增成功',
                        type: 'success',
                    })
                }
                goBack()
            })
        }
    })
}
</script>

<style lang="scss" scoped>
:deep(.el-pagination) {
    position: unset;
}

.code-box {
    display: flex;
    justify-content: center;
    flex-direction: column;
    align-items: center;
    border: 3px solid #437bf7;
    height: 285px;
    width: 260px;
    border-radius: 20px;
}

.title {
    font-size: 14px;
    display: flex;
    // text-align: center;
}

.layout-code {
    display: flex;
    // justify-content: space-between;
    justify-content: space-around;
}
</style>
